<?php
/**
* https://gitee.com/foglede SAE本地服务初始化脚本
* https://gitee.com/foglede
*/
ini_set('max_execution_time', 0);
ini_set('memory_limit', -1); 
set_time_limit(0);
ignore_user_abort(TRUE);
include __dir__.DIRECTORY_SEPARATOR.'loadmahuohuosae.php';
echo mb_convert_encoding('新浪微博：https://gitee.com/foglede', 'GBK', 'auto'),PHP_EOL;

function run($dir,$pstr,&$runresources = null){
  $runresources = proc_open($dir,array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w') ),$pipesarray);
  stream_set_blocking($pipesarray[1],0);
//socket_set_nonblock($pipesarray[1]);
  echo iconv('UTF-8','GBK',$pstr).PHP_EOL;
  passthru('start https://gitee.com/foglede');
  passthru('start http://127.0.0.1/mahuohuo/index.php');
  return proc_get_status($runresources);
}

register_shutdown_function(function(){
  echo iconv('UTF-8','GBK','遇到致命错误！').PHP_EOL;
//MYSQL有遗留进程，MYSQL在windows开启方式很奇异。NEW主进程和子进程，主进程退出，子进程上升主进程
});

/*** mahuohuo.com 修改配置 ***/
$rundir = array('apache'/**,'mysql'**/,'php','redis');
//匹配目录。
$argv = realpath(__dir__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR.'mahuohuo');
$rundir = array_combine($rundir, glob($argv.DIRECTORY_SEPARATOR.'*', GLOB_MARK  )  );

//检查模板配置
if(!is_file($rundir['php'].DIRECTORY_SEPARATOR.'php.mahuohuo')){
    die(iconv('UTF-8','GBK','SAEPHP仿真配置文件错误或失效，无法继续！'));
}

if(!is_file($rundir['apache'].DIRECTORY_SEPARATOR.'conf'.DIRECTORY_SEPARATOR.'phpfastcgi.mahuohuo')){
    die(iconv('UTF-8','GBK','Apache高性能配置文件错误或失效，无法继续！'));
}

//无论如何都替换
$apcacheconf = file_get_contents($rundir['apache'].DIRECTORY_SEPARATOR.'conf'.DIRECTORY_SEPARATOR.'phpfastcgi.mahuohuo');
$apcacheconf = str_replace(array('[$DIR]','[$DIRC]'),array($rundir['php'],__dir__),$apcacheconf);
file_put_contents($rundir['apache'].DIRECTORY_SEPARATOR.'conf'.DIRECTORY_SEPARATOR.'phpfastcgi.txt',$apcacheconf,LOCK_EX);

$apcacheconf = file_get_contents($rundir['php'].'php.mahuohuo');
$apcacheconf = str_replace('extension_dir = "./ext"','extension_dir = "'.$rundir['php'].'ext"',$apcacheconf);
file_put_contents($rundir['php'].DIRECTORY_SEPARATOR.'php.ini',$apcacheconf,LOCK_EX);
file_put_contents($rundir['php'].DIRECTORY_SEPARATOR.'php.ini',
"\r\n".'disable_classes = XMLWriter,DOMDocument,DOMNotation,DOMXPath,PDOException,PDO,PDOStatement,PDORow,SQLiteDatabase,SQLiteResult,SQLiteUnbuffered,SQLiteException'."\r\n".
'disable_functions = php_real_logo_guid,php_egg_logo_guid,php_ini_scanned_files,php_ini_loaded_file,readlink,linkinfo,symlink,link,exec,system,escapeshellcmd,escapeshellarg,passthru,shell_exec,proc_open,proc_close,proc_terminate,proc_get_status,proc_nice,getmyuid,getmygid,getmyinode,putenv,getopt,sys_getloadavg,getrusage,get_current_user,magic_quotes_runtime,set_magic_quotes_runtime,import_request_variables,debug_zval_dump,ini_alter,dl,pclose,popen,stream_socket_client,stream_socket_server,stream_socket_accept,stream_socket_pair,set_file_buffer,stream_get_transports,get_headers,mail,openlog,syslog,closelog,apc_add,apc_clear_cache,apc_compile_file,apc_define_constants,apc_delete,apc_load_constants,apc_sma_info,apc_store,flock,pfsockopen,posix_kill,apache_child_terminate,apache_get_modules,apache_get_version,apache_getenv,apache_lookup_uri,apache_reset_timeout,apache_response_headers,apache_setenv,virtual,mysql_pconnect,memcache_add_server,memcache_connect,memcache_pconnect'
, FILE_APPEND);

//$apacheconf = glob($rundir['mysql'].'data'.DIRECTORY_SEPARATOR.'mysql'.DIRECTORY_SEPARATOR.'*.mahuohuo', GLOB_MARK  );
//$argv = array_flip(array('user.MYD','user.MYI','user.frm'));
//foreach($apacheconf as $f){  
//  if(is_file($f) && array_key_exists(basename($f,'.mahuohuo'),$argv ) ){
//    $argc = copy($f,dirname($f).DIRECTORY_SEPARATOR.basename($f,'.mahuohuo'));
//  }else if(!$argc){
//    die(iconv('UTF-8','GBK','数据库文件'.basename($f).'‘扩皮’错误，无法继续'));
//  }else{
//    die(iconv('UTF-8','GBK','数据库文件'.basename($f).'不存在错误，无法继续'));
//  }
//}
/*** mahuohuo.com 修改配置完 ***/

run($rundir['redis'].'redis-server.exe '.$rundir['redis'].'redis.conf','本地存储，队列监听成功运行',$redisresources);
//run($rundir['redis'].'bin'.DIRECTORY_SEPARATOR.'mysqld','MYSQL运行成功',$mysqlresources);
run($rundir['apache'].'bin'.DIRECTORY_SEPARATOR.'httpd','Apache运行成功',$apacheresources);
echo iconv('UTF-8','GBK','开启队列监听……').PHP_EOL;
//添加单个任务
$redis = new redis();
$listred = $redis->connect('127.0.0.1', 6379);
while($listred){
    $alltaskqueue = $redis->keys(queuefilename . '*');
    echo 'mahuohuo::'.count($alltaskqueue),iconv('UTF-8','GBK','个队列任务集合').PHP_EOL;
    $tasklist = array_pop($alltaskqueue);
    if( is_null($tasklist) ){
       echo iconv('UTF-8','GBK','似乎不存在mahuohuo队列任务'),PHP_EOL;
    }  else {
       echo iconv('UTF-8','GBK','开始运行名为'),$tasklist,iconv('UTF-8','GBK','的所有任务').PHP_EOL;
       $tasklistrunends = $redis->get($tasklist);
       $tasklistrunends = unserialize($tasklistrunends);
       if(! is_array($tasklistrunends) ){$tasklistrunends = FALSE;}
       //var_dump($tasklist);
       do{
           //echo iconv('UTF-8','GBK','获取的所有网址为'),$tasklist,iconv('UTF-8','GBK','~').PHP_EOL;
           //var_dump($tasklist);
           array_map(function($key){
               sleep(20);
               $key['postdata'] = base64_decode($key['postdata']);
               //$key['postdata'] = explode('=', $key['postdata']);
               //$key['postdata'] = http_build_query($key['postdata'],'');
               //var_dump($key);
              $postcontext = array(
                'http' => array(
                    'method'  => 'POST',
                    'header'  => implode("\r\n", array(
                         'Content-Type: application/x-www-form-urlencoded',
                         'User-Agent:mahuohuo.Com WebService',
                         'Content-Length: '.strlen($key['postdata'])
                    )),
                    //'content' => http_build_query($key['postdata'], '', '&'),
                    'content' => http_build_query($key['postdata']),
                    'encoding' => 'UTF-8'
                )
            );
              $posthant = stream_context_create($postcontext);
              $posthant = file_get_contents(urldecode($key['url']), false, $posthant);
            //echo iconv('UTF-8','GBK','地址'),$key['postdata'],iconv('UTF-8','GBK','获取的内容为'),PHP_EOL, mb_convert_encoding($posthant,'GBK').PHP_EOL;
               if($posthant >= 0){
                   echo iconv('UTF-8', 'GBK', urldecode($key['url']).'，执行成功！').PHP_EOL;
               }
            //return true;
           },$tasklistrunends);
           
           sleep(10);
           echo 'mahuohuo 休息下哦！'.PHP_EOL;
           $tasklistrunends = !($redis->delete($tasklist) >= 1);
           break;
           echo $tasklistrunends;
       }
       while ($tasklistrunends === FALSE);
    }
    echo iconv('UTF-8','GBK','等待新的队列~'),PHP_EOL;
    sleep(60);
}

?>